package com.macro.mall.portal.controller;

import com.macro.mall.common.api.CommonResult;
import com.macro.mall.portal.domain.User;
import com.macro.mall.portal.domain.vo.MsgVo;
import com.macro.mall.portal.domain.vo.PageVo;
import com.macro.mall.portal.service.IUserService;
import com.macro.mall.portal.util.ConcurrentHashMapCacheUtils;
import com.macro.mall.portal.util.MyHttpUtil;
import com.macro.mall.portal.util.SignatureUtil;

import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/wx")
public class WechatIndexController {

    private static final Logger LOGGER = LoggerFactory.getLogger(WechatIndexController.class);

    @Autowired
    private IUserService userService;

    @RequestMapping(value = "/res", method = RequestMethod.GET)
    @ApiOperation("验证")
    public void get(HttpServletRequest request, HttpServletResponse response) {
        // 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr");
        System.out.println("signature : " + signature + "timestamp :" + timestamp + "nonce: " + nonce + "echostr: " + echostr);
        PrintWriter out = null;
        try {
            out = response.getWriter();
            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，否则接入失败
            if (SignatureUtil.checkSignature(signature, timestamp, nonce)) {
                out.print(echostr);
            }
        } catch (IOException e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage());
        } finally {
            out.close();
            out = null;
        }
    }

    @RequestMapping(value = "/save", method = RequestMethod.GET)
    @ApiOperation("获取openId")
    public void saveOpenId(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 用户同意授权，获得的code
        String code = request.getParameter("code");
//        String username = request.getParameter("phoneNum");
//        String appid = "wxe4e2be40e7606eca"; //公众号appid
        String appid = "wx9e30c3907000204c"; //金池公众号appid
//        String appsecret = "64987d552d17bf51ebac2697e91c70d5";//公众号密钥
        String appsecret = "ec8360dcd3144ba26f432e5ceaef2584";//金池 公众号密钥

        // 获取access_token和openid
        String apiurl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + appsecret
                + "&code=" + code + "&grant_type=authorization_code";

//        JSONObject jsonObject = MyHttpUtil.sendJsonGET(apiurl);
//
////        String access_token = jsonObject.getString("access_token");
//        String openid = jsonObject.getString("openid");
//
//        System.out.println("用户openid====" + openid);
//        //用户注册
//        userService.registered(User.builder().openId(openid).build());
        try {
            JSONObject jsonObject = MyHttpUtil.sendJsonGET(apiurl);
            String openid = jsonObject.getString("openid");
            System.out.println("用户openid====" + openid);
//            String redirectUrl = "https://vx.szdrkg.com/tools.html?openid=" + openid;
            String redirectUrl = "https://vx.szdrkg.com/index.html#/pages/index/index?openid=" + openid;
            //用户注册
            userService.registered(User.builder().openId(openid).build());
            response.sendRedirect(redirectUrl);
        } catch (Exception e) {
            e.printStackTrace();
            new Exception("服务器内部异常");
        }
    }


    @RequestMapping(value = "/center", method = RequestMethod.GET)
    @ApiOperation("获取openId&&个人中心")
    public void center(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 用户同意授权，获得的code
        String code = request.getParameter("code");
//        String username = request.getParameter("phoneNum");
//        String appid = "wxe4e2be40e7606eca"; //公众号appid
//        String appsecret = "64987d552d17bf51ebac2697e91c70d5";//公众号密钥

        String appid = "wx9e30c3907000204c"; //金池公众号appid
        String appsecret = "ec8360dcd3144ba26f432e5ceaef2584";//金池 公众号密钥

        // 获取access_token和openid
        String apiurl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + appsecret
                + "&code=" + code + "&grant_type=authorization_code";
        try {
            JSONObject jsonObject = MyHttpUtil.sendJsonGET(apiurl);
            String openid = jsonObject.getString("openid");
            System.out.println("用户openid====" + openid);
//            String redirectUrl = "http://vx.szdrkg.com/personal-center.html?openid=" + openid;
            String redirectUrl = "http://vx.szdrkg.com/index.html#/pages/user/user?openid=" + openid;
            //用户注册
            userService.registered(User.builder().openId(openid).build());
            response.sendRedirect(redirectUrl);
        } catch (Exception e) {
            e.printStackTrace();
            new Exception("服务器内部异常");
        }
    }

    @RequestMapping(value = "/personCent", method = RequestMethod.GET)
    @ApiOperation("获取openId&&个人中心")
    public void personCent(HttpServletRequest request, HttpServletResponse response) throws Exception {
//// 用户同意授权，获得的code
        String code = request.getParameter("code");
////        String username = request.getParameter("phoneNum");
////        String appid = "wxe4e2be40e7606eca"; //公众号appid
////        String appsecret = "64987d552d17bf51ebac2697e91c70d5";//公众号密钥

        String appid = "wx9e30c3907000204c"; //金池公众号appid
        String appsecret = "ec8360dcd3144ba26f432e5ceaef2584";//金池 公众号密钥

        // 获取access_token和openid
        String apiurl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + appsecret
                + "&code=" + code + "&grant_type=authorization_code";
        try {
            JSONObject jsonObject = MyHttpUtil.sendJsonGET(apiurl);
            String openid = jsonObject.getString("openid");
            System.out.println("用户openid====" + openid);
////            String redirectUrl = "http://vx.szdrkg.com/personal-center.html?openid=" + openid;
            String redirectUrl = "https://vx.szdrkg.com/index.html#/pages/user/user?openid=" + openid;
            //用户注册
            userService.registered(User.builder().openId(openid).build());
            response.sendRedirect(redirectUrl);
        } catch (Exception e) {
            e.printStackTrace();
            new Exception("服务器内部异常");
        }
    }

    @RequestMapping(value = "/pay", method = RequestMethod.GET)
    @ApiOperation("收款码入口")
    public void pay(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 用户同意授权，获得的code
        String code = request.getParameter("code");

        String appid = "wx9e30c3907000204c"; //金池公众号appid
        String appsecret = "ec8360dcd3144ba26f432e5ceaef2584";//金池 公众号密钥

        // 获取access_token和openid
        String apiurl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + appsecret
                + "&code=" + code + "&grant_type=authorization_code";
        try {
            JSONObject jsonObject = MyHttpUtil.sendJsonGET(apiurl);
            String openid = jsonObject.getString("openid");
            System.out.println("用户openid====" + openid);
            String redirectUrl = "https://vx.szdrkg.com/index.html#/pages/addWallet/addWallet?openid=" + openid;
            //用户注册
            userService.registered(User.builder().openId(openid).build());
            response.sendRedirect(redirectUrl);
        } catch (Exception e) {
            e.printStackTrace();
            new Exception("服务器内部异常");
        }
    }

    @RequestMapping(value = "/refund", method = RequestMethod.GET)
    @ApiOperation("退款入口")
    public void refund(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 用户同意授权，获得的code
        String code = request.getParameter("code");

        String appid = "wx9e30c3907000204c"; //金池公众号appid
        String appsecret = "ec8360dcd3144ba26f432e5ceaef2584";//金池 公众号密钥

        // 获取access_token和openid
        String apiurl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + appsecret
                + "&code=" + code + "&grant_type=authorization_code";
        try {
            JSONObject jsonObject = MyHttpUtil.sendJsonGET(apiurl);
            String openid = jsonObject.getString("openid");
            System.out.println("用户openid====" + openid);
            String redirectUrl = "https://vx.szdrkg.com/index.html#/pages/payPage/outPay?openid=" + openid;
            //用户注册
            userService.registered(User.builder().openId(openid).build());
            response.sendRedirect(redirectUrl);
        } catch (Exception e) {
            e.printStackTrace();
            new Exception("服务器内部异常");
        }
    }

    @RequestMapping(value = "/loanShare", method = RequestMethod.GET)
    @ApiOperation("获取openId提交我能贷")
    public void loanShare(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 用户同意授权，获得的code
        String code = request.getParameter("code");
        String appid = "wx9e30c3907000204c"; //金池公众号appid
        String appsecret = "ec8360dcd3144ba26f432e5ceaef2584";//金池 公众号密钥
        // 获取access_token和openid
        String apiurl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + appsecret
                + "&code=" + code + "&grant_type=authorization_code";
        try {
            JSONObject jsonObject = MyHttpUtil.sendJsonGET(apiurl);
            String openid = jsonObject.getString("openid");
            System.out.println("用户openid====" + openid);
            String redirectUrl = "https://vx.szdrkg.com/my-loan.html?openid=" + openid;
            //用户注册
            userService.registered(User.builder().openId(openid).build());
            response.sendRedirect(redirectUrl);
        } catch (Exception e) {
            e.printStackTrace();
            new Exception("服务器内部异常");
        }
    }

    @RequestMapping(value = "/checkIdent", method = RequestMethod.POST)
    @ApiOperation("验证用户是否关注公众号")
    public CommonResult checkIdent(@RequestBody PageVo vo) throws Exception {
        if (StringUtils.isEmpty(vo.getOpenId())) {
            return CommonResult.failed("openid不能为空");
        }
        boolean check = ConcurrentHashMapCacheUtils.check("access_token");
        if (check == false) {
            String accountToken = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx59d87a41d72f796b&secret=ec8360dcd3144ba26f432e5ceaef2584";
            JSONObject jsonObject = MyHttpUtil.sendJsonGET(accountToken);
            String token = jsonObject.getString("access_token");
            int expiresIn = jsonObject.getInt("expires_in");

            ConcurrentHashMapCacheUtils.setCache("access_token", token, expiresIn * 1000L);
        }
        //119.123.68.237
        try {
            String accessToken = (String) ConcurrentHashMapCacheUtils.getCache("access_token");
//            String accessToken = (String) redisTool.get("access_token");
            String userInfo = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken + "&openid=" + vo.getOpenId() + "&lang=zh_CN";
            JSONObject jsonObject = MyHttpUtil.sendJsonGET(userInfo);
            int subscribe = jsonObject.getInt("subscribe");
            if (subscribe == 0) {
                return CommonResult.failed("用户未关注");
            }
            return CommonResult.success(null, "用户已关注");
        } catch (Exception e) {
            e.printStackTrace();
            String accountToken = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx59d87a41d72f796b&secret=ec8360dcd3144ba26f432e5ceaef2584";
            JSONObject jsonObject = MyHttpUtil.sendJsonGET(accountToken);
            String token = jsonObject.getString("access_token");
            int expiresIn = jsonObject.getInt("expires_in");
            ConcurrentHashMapCacheUtils.setCache("access_token", token, expiresIn * 1000L);
            return CommonResult.failed("微信缓存！请刷新一下页面");
        }
    }

    @RequestMapping(value = "/js", method = RequestMethod.POST)
    @ApiOperation("获取js参数")
    public CommonResult js(@RequestBody MsgVo msgVo) throws Exception {
        boolean check = ConcurrentHashMapCacheUtils.check("access_token");
        if (check == false) {
            //中悦
//            String accountToken = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx59d87a41d72f796b&secret=e9590210a539cbc5bc620031b5254592";
            String accountToken = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx9e30c3907000204c&secret=ec8360dcd3144ba26f432e5ceaef2584";
            JSONObject jsonObject = MyHttpUtil.sendJsonGET(accountToken);
            String token = jsonObject.getString("access_token");
            int expiresIn = jsonObject.getInt("expires_in");
            ConcurrentHashMapCacheUtils.setCache("access_token", token, expiresIn * 1000L);
        }
        String accessToken = (String) ConcurrentHashMapCacheUtils.getCache("access_token");
        try {
            String jsapi_ticket = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi";
            JSONObject jsonObject = MyHttpUtil.sendJsonGET(jsapi_ticket);
            String ticket = jsonObject.getString("ticket");
            Map<String, String> map = sign(ticket, msgVo.getUrl());
            return CommonResult.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            String accountToken = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx59d87a41d72f796b&secret=e9590210a539cbc5bc620031b5254592";
            JSONObject jsonObject = MyHttpUtil.sendJsonGET(accountToken);
            String token = jsonObject.getString("access_token");
            int expiresIn = jsonObject.getInt("expires_in");
            ConcurrentHashMapCacheUtils.setCache("access_token", token, expiresIn * 1000L);
            return CommonResult.failed("微信缓存！请刷新一下页面");
        }



    }


    public static Map<String, String> sign(String jsapi_ticket, String url) {
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = "qwasdfzxcvdsad";
        String timestamp = create_timestamp();

        //注意这里参数名必须全部小写，且必须有序
        String sign = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;
        System.out.println(sign);

        String signature = DigestUtils.sha1Hex(sign);

        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);
        return ret;
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }


}
